﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using IntroMongo.DAL;
using IntroMongo.Models;
using MongoDB.Bson;

namespace IntroMongo.Controllers
{
    public class PerformanceController : Controller
    {
        //
        // GET: /Performance/

        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Index(int numberOfUser)
        {
            var initTime = DateTime.Now;
            if (numberOfUser > 0)
            {
                CreateUserNoSql(numberOfUser);
            }
            var endTime = DateTime.Now;
            var result = (endTime - initTime).TotalSeconds;
            ViewBag.TotalTime = result;
            ViewBag.TotalUser = numberOfUser;

            return View("ResultNoSql");
        }

        public ActionResult SQL()
        {
            return View();
        }

        [HttpPost]
        public ActionResult SQL(int numberOfUser)
        {
            var initTime = DateTime.Now;
            if (numberOfUser > 0)
            {
                CreateUserNoSql(numberOfUser);
            }
            var endTime = DateTime.Now;
            var result = (endTime - initTime).TotalSeconds;
            ViewBag.TotalTime = result;
            ViewBag.TotalUser = numberOfUser;

            return View("ResultSql");
        }


        private void CreateUserNoSql(int numberOfUser)
        {
            // Get user collection reference
            var users = MongoWrapper.Instance().GetCollection("users");

            Parallel.For(0, numberOfUser, (i) => {
                // Create BsonDocument object for new user
                var user = new BsonDocument();
                user["firstname"] = "FirstName" + i;
                user["lastname"] = "LastName" + i;
                user["age"] = i;
                user["createdate"] = DateTime.Now;
                // Insert new user object to collection
                users.Insert(user);
            });
        }

        private void CreateUserSql(int numberOfUser)
        {
            // Get user collection reference
            var users = MongoWrapper.Instance().GetCollection("users");
            var provider = new MongoDBSQL();

            Parallel.For(0, numberOfUser, (i) =>
            {
                provider.AddUser("FirstName" + i, "LastName" + i, i);
            });
        }

    }
}
